from typing import Optional
from fastapi import APIRouter, HTTPException
from apps.schemas.schemas import CategoryCreateRequest, CategoryUpdateRequest
from apps.services.category import get_all_categories, create_category, update_category, delete_category

categories = APIRouter()


@categories.get("/msg")
async def get_all_categories_api():
    try:
        categories_data = await get_all_categories()
        return {"status": 200, "message": "success", "data": categories_data}
    except Exception as e:
        return {"status": 500, "message": f"Error retrieving categories: {str(e)}"}


@categories.post("/add")
async def create_category_api(data: CategoryCreateRequest):
    try:
        category_data = await create_category(data)
        return {
            "status": 201,
            "message": "Category created successfully",
            "data": category_data
        }
    except ValueError as e:
        return {"status": 400, "message": str(e)}
    except Exception as e:
        return {"status": 500, "message": f"Error creating category: {str(e)}"}


@categories.put("/update/{category_id}")
async def update_category_api(category_id: int, data: CategoryUpdateRequest):
    try:
        updated = await update_category(category_id, data)
        if updated:
            return {"status": 200, "message": "Category updated successfully"}
        else:
            return {"status": 404, "message": "Category not found"}
    except Exception as e:
        return {"status": 500, "message": f"Error updating category: {str(e)}"}


@categories.delete("/delete/{category_id}")
async def delete_category_api(category_id: int):
    try:
        deleted = await delete_category(category_id)
        if deleted:
            return {"status": 200, "message": "Category and associated programs deleted successfully"}
        else:
            return {"status": 404, "message": "Category not found"}
    except Exception as e:
        return {"status": 500, "message": f"Error deleting category: {str(e)}"}
